package springGateway;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import com.alibaba.fastjson.JSONObject;
import camila.common.filter.determine.RedisValide;
import camila.common.filter.redis.RedisUtil;
import camila.zuul.filters.TokenFilter;
import camila.zuul.filters.TokenFilter.ResponseWrapperFilter;
import camila.zuul.filters.common.DetermineValideSupport;

@Configuration
public class MyConfig{
	@Bean
	@Qualifier("myRedisTemplate")
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
		return RedisUtil.configureJsonRedisTemplate(factory);
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Bean
	public RedisUtil redisUtil(@Qualifier("myRedisTemplate") RedisTemplate template) {
		return new RedisUtil(template);
	}
	 
	 @Bean
	 public TokenFilter tokenFilter(RedisUtil redisUtil) {
		 TokenFilter tokenFilter = new TokenFilter(new RedisValide(redisUtil),"token");
		 tokenFilter.addWrapper("/test/login", new DetermineValideSupport.ResponseBodyWrapper() {


			@Override
			public String buildToken(String body, Map<String, Object> value) {
				value.put("opeTime", new Date().toString());
				JSONObject jo = (JSONObject)JSONObject.parse(body);
				value.put("token", jo.getString("autorizer"));
				System.err.println("body:"+body);
				return String.valueOf(value.get("token"));
			}

			@Override
			public String getResult(String body, String token, Map<String, Object> value) {
				value.put("body", body);
				return JSONObject.toJSONString(value);
			}
			 
		 }); 
		 return tokenFilter;
	 }
	 
	 @Bean 
	 public ResponseWrapperFilter responseWrapperFilter(RedisUtil redisUtil) {
		 return tokenFilter(redisUtil).getResponseWrapperFilter();
	 }
}
